package com.flydog.taskManager.service.impl;

import com.flydog.taskManager.dto.TaskBriefParam;
import com.flydog.taskManager.entity.TaskBrief;
import com.flydog.taskManager.repository.TaskBriefRepository;
import com.flydog.taskManager.service.TaskBriefService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class TaskBriefServiceImpl implements TaskBriefService {

    @Autowired
    private TaskBriefRepository taskBriefRepository;

    @Override
    public TaskBrief create(TaskBriefParam param) {
        TaskBrief brief = new TaskBrief();
        BeanUtils.copyProperties(param, brief);
        brief.setCreateTime(Calendar.getInstance().getTime());
        return taskBriefRepository.save(brief);
    }

    @Override
    public TaskBrief update(Long briefId, TaskBriefParam brief) {
        TaskBrief taskBrief = taskBriefRepository.getOne(briefId);
        BeanUtils.copyProperties(brief, taskBrief);
        return taskBriefRepository.save(taskBrief);
    }

    @Override
    public List<TaskBrief> delete(Long[] briefIds) {
        List<TaskBrief> result = new ArrayList<>();
        for (Long briefId : briefIds) {
            Optional<TaskBrief> optionalTaskBrief = taskBriefRepository.findById(briefId);
            if (optionalTaskBrief.isPresent()) {
                taskBriefRepository.deleteById(briefId);
                result.add(optionalTaskBrief.get());
            }
        }
        return result;
    }

    @Override
    public List<TaskBrief> listByPhaseTaskId(Long taskId) {
        return taskBriefRepository.findByPhaseTaskIdOrderByCreateTimeDesc(taskId);
    }

    @Override
    public List<TaskBrief> listByPeriodicTaskId(Long taskId) {
        return taskBriefRepository.findByPeriodicTaskIdOrderByCreateTimeDesc(taskId);
    }
}
